
import java.io.File;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class TakeScreenCompletionHandler implements Runnable {

	private String mirrorPath = null;
	
	private Information info = null;
	
	private ScreenShotDAO dao = null;
	
	private CompletionService<ScreenShotVO> takeScreencompletionService = null;
	
	public TakeScreenCompletionHandler(String mirrorPath, Information info,
			CompletionService<ScreenShotVO> takeScreencompletionService) {
		this.mirrorPath = mirrorPath;
		this.info = info;
		dao = new ScreenShotDAO();
		this.takeScreencompletionService = takeScreencompletionService;
	}
	
	@Override
	public void run() {
		while( true ) {
			try {
				Future<ScreenShotVO> future = takeScreencompletionService.take();
				ScreenShotVO screenShotVO = future.get();
				if( screenShotVO != null ) {
					if( dao.insertScreenShot(screenShotVO) ) {
						String filename = screenShotVO.getFileName();
						File thmbFile = new File(mirrorPath+filename.substring(filename.lastIndexOf("/")));
						UrlToImage.makeThumbnailImage(thmbFile);
						info.incrementSuccess();
					}
					else {
						if( dao.insertScreenShot(screenShotVO) ) {
							String filename = screenShotVO.getFileName();
							File thmbFile = new File(mirrorPath+filename.substring(filename.lastIndexOf("/")));
							UrlToImage.makeThumbnailImage(thmbFile);
							info.incrementSuccess();
						}
						else
							info.incrementFailure();
					}
				}
				else {
					info.incrementFailure();
				}
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
				return;
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
	}
}
